package hedron.db.model;

import hedron.Application;
import hedron.db.DBManager;
import java.sql.Connection;
import java.sql.ResultSet;

public class StockGroup extends AbstractModel {

	private long GROUP_ID = 0;
	public String GROUP_NAME = EMPTY_STR;

	@Override
	public long getID() {
		return GROUP_ID;
	}

	@Override
	public String getIDName() {
		return "GROUP_ID";
	}

	@Override
	public String getTableName() {
		return "HSTOCKGROUP";
	}

	public StockGroup() {}

	public StockGroup(ResultSet rs) {
		if (rs == null) {
			throw new IllegalArgumentException("ResultSet might not be null");
		}
		if (!load(rs)) {
			throw new IllegalArgumentException("cannot load from ResultSet");
		}
	}

	@Override
	public boolean load(ResultSet rs) {
		DBManager db = Application.DB;
		GROUP_ID = db.getLong(rs, getIDName(), 0);
		if (GROUP_ID == 0) {
			return false;
		}
		GROUP_NAME = db.getString(rs, "GROUP_NAME");
		return true;
	}

	@Override
	public boolean isValid() {
		return isNotEmpty(GROUP_NAME);
	}

	@Override
	public boolean store(Connection conn) {
		StringBuilder sql = new StringBuilder();

		if (GROUP_ID <= 0) {// insert
			GROUP_ID = Application.ID.getNewID();
			sql.append("insert into ");
			sql.append(getTableName());
			sql.append("(GROUP_ID, GROUP_NAME) values(?,?)");
			return db.ddlQuery(conn, sql.toString(), GROUP_ID, GROUP_NAME);
		} else {// update
			sql.append("update ");
			sql.append(getTableName());
			sql.append(" SET GROUP_NAME = ?");
			sql.append(" where GROUP_ID = ").append(GROUP_ID);
			return db.ddlQuery(conn, sql.toString(), GROUP_NAME);
		}
	}

	@Override
	public boolean delete(Connection conn) {
		return false;
	}

}
